package me.zhengjie.modules.easycode.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.AllArgsConstructor;
import me.zhengjie.constant.DefaultConfig;
import me.zhengjie.modules.easycode.domain.Project;
import me.zhengjie.modules.easycode.domain.ProjectTmg;
import me.zhengjie.modules.easycode.domain.TypeMapper;
import me.zhengjie.modules.easycode.domain.*;
import me.zhengjie.modules.easycode.service.TypeMapperService;
import me.zhengjie.modules.easycode.service.dto.TypeMapperGroupListDto;
import me.zhengjie.modules.easycode.service.dto.TypeMapperQueryParam;
import me.zhengjie.modules.easycode.service.mapper.ProjectMapper;
import me.zhengjie.modules.easycode.service.mapper.ProjectTmgMapper;
import me.zhengjie.modules.easycode.service.mapper.TypeMapperGroupMapper;
import me.zhengjie.modules.easycode.service.mapper.TypeMapperMapper;
import me.zhengjie.utils.Result;
import me.zhengjie.utils.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author guoqing
 * @date 2021-06-17
 */
@Service
@AllArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class TypeMapperServiceImpl implements TypeMapperService {

    private final TypeMapperMapper typeMapperMapper;
    private final ProjectTmgMapper projectTmgMapper;
    private final TypeMapperGroupMapper typeMapperGroupMapper;
    private final ProjectMapper projectMapper;


    @Override
    public Result getTypeMapperGroupList(TypeMapperQueryParam queryParam) {
        final Long userId = SecurityUtils.getCurrentUserId();
        //验证空值信息
        Result verificationNull = verificationNull(queryParam, userId);
        if (verificationNull != null) return verificationNull;

        //查询当前项目
        final Project project = projectMapper.selectOne(new QueryWrapper<Project>().eq("project_code", queryParam.getProjectCode()).eq("userid", userId));
        if (ObjectUtil.isEmpty(project)) {
            return Result.error(queryParam.getProjectCode() + "项目已经不存在");
        }

        final TypeMapperGroupListDto groupListDto = new TypeMapperGroupListDto();

        /**
         * 设置并返回当前类型映射组和映射集合信息
         */
        setCurrentTypeMapper(project, groupListDto, queryParam.getCurrentTypeMapperGroupid());
        /**
         * 保存项目组信息
         */
        projectMapper.updateById(project);
        return Result.success(groupListDto);
    }

    /**
     * 验证空值
     *
     * @param queryParam
     * @param userId
     * @return
     */
    private Result verificationNull(TypeMapperQueryParam queryParam, Long userId) {
        if (ObjectUtil.isEmpty(queryParam)) {
            return Result.error("参数信息缺失");
        }
        if (userId == null || userId.equals(0)) {
            return Result.error("用户不存在");
        }
        if (StrUtil.isEmpty(queryParam.getProjectCode())) {
            return Result.error("项目编码不存在");
        }
        return null;
    }

    // 设置当前类型映射器组
    private void setCurrentTypeMapper(Project project, TypeMapperGroupListDto groupListDto, Integer typeMapperGroupId) {

        TypeMapperGroup typeMapperGroup = null;
        if (project.getCurrentTmGroupId() == null || project.getCurrentTmGroupId().equals(0)) {
            //如果当前模版不存在，则新增绑定默认
            typeMapperGroup = typeMapperGroupMapper.selectOne(new QueryWrapper<TypeMapperGroup>().eq("group_name", DefaultConfig.DEFAULT));
            //设置当前类型映射器组
            project.setCurrentTmGroupId(typeMapperGroup.getId());
            //插入项目关联默认类型映射器组
            insertProjectTmg(project, typeMapperGroup);
        } else {
            //设置当前类型映射器组
            if (typeMapperGroupId != null && !typeMapperGroupId.equals(0)) {
                project.setCurrentTmGroupId(typeMapperGroupId);
            }
            //如果当前模版组存在，则使用当前模板组
            typeMapperGroup = typeMapperGroupMapper.selectById(project.getCurrentTmGroupId());
            //非当前类型映射器组
            final List<TypeMapperGroup> list = typeMapperGroupMapper.selectListByProjectId(project.getProjectId());
            groupListDto.setTypeMapperGroups(list);
        }
        // 当前组类型映射集合
        if (ObjectUtil.isNotEmpty(typeMapperGroup)) {
            groupListDto.setCurrentTypeMapperGroup(typeMapperGroup);
            final List<TypeMapper> typeMappers = typeMapperMapper.selectList(new QueryWrapper<TypeMapper>().eq("group_id", typeMapperGroup.getId()));
            groupListDto.setTypeMappers(typeMappers);
        }
    }

    /**
     * 插入项目和类型映射器组关联
     *
     * @param project
     * @param typeMapperGroup
     */
    private void insertProjectTmg(Project project, TypeMapperGroup typeMapperGroup) {
        final ProjectTmg tmg = new ProjectTmg();
        tmg.setProjectId(project.getProjectId());
        tmg.setTypeMapperGroupId(typeMapperGroup.getId());
        projectTmgMapper.insert(tmg);
    }
}
